<template>
  <div class="enhanced-trend-analysis">
    <!-- 时间筛选器 -->
    <div class="filter-section">
      <div class="filter-header">
        <h3 class="section-title">
          <el-icon><TrendCharts /></el-icon>
          趋势分析
        </h3>
        <div class="filter-controls">
          <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
            <el-radio-button label="today">今日</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
          
          <el-date-picker
            v-if="timeRange === 'custom'"
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleCustomDateChange"
            style="margin-left: 12px;"
          />
        </div>
      </div>
      
      <!-- 维度选择 -->
      <div class="dimension-controls">
        <el-select v-model="selectedDimension" placeholder="选择统计维度" style="width: 150px;">
          <el-option label="按状态" value="status" />
          <el-option label="按分类" value="category" />
          <el-option label="按处理人" value="assignee" />
          <el-option label="按优先级" value="priority" />
        </el-select>
        
        <el-select v-model="chartType" placeholder="选择图表类型" style="width: 120px; margin-left: 12px;">
          <el-option label="折线图" value="line" />
          <el-option label="柱状图" value="bar" />
          <el-option label="饼图" value="pie" />
        </el-select>
        
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 主要趋势图表 -->
      <el-card class="main-chart-card">
        <template #header>
          <div class="chart-header">
            <span class="chart-title">{{ getChartTitle() }}</span>
            <div class="chart-actions">
              <el-button size="small" @click="exportChart">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
              <el-button size="small" @click="fullscreenChart">
                <el-icon><FullScreen /></el-icon>
                全屏
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="chart-container" ref="mainChartContainerRef">
          <div v-if="loading" class="chart-loading">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <div v-else-if="!chartData || chartData.length === 0" class="chart-empty">
            <el-icon><DataLine /></el-icon>
            <span>暂无数据</span>
          </div>
          <canvas v-else ref="mainChartRef"></canvas>
        </div>
      </el-card>

      <!-- 辅助图表 -->
      <div class="secondary-charts">
        <el-card class="secondary-chart-card">
          <template #header>
            <span class="chart-title">工单状态分布</span>
          </template>
          <div class="chart-container" ref="statusChartContainerRef">
            <div v-if="loading" class="chart-loading">
              <el-icon class="loading-icon"><Loading /></el-icon>
            </div>
            <canvas v-else ref="statusChartRef"></canvas>
          </div>
        </el-card>

        <el-card class="secondary-chart-card">
          <template #header>
            <span class="chart-title">处理人工作量</span>
          </template>
          <div class="chart-container" ref="assigneeChartContainerRef">
            <div v-if="loading" class="chart-loading">
              <el-icon class="loading-icon"><Loading /></el-icon>
            </div>
            <canvas v-else ref="assigneeChartRef"></canvas>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="data-table-card">
      <template #header>
        <div class="table-header">
          <span class="table-title">详细数据</span>
          <div class="table-actions">
            <el-button size="small" @click="exportData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="total" label="总数" width="100" />
        <el-table-column prop="pending" label="待处理" width="100" />
        <el-table-column prop="inProgress" label="处理中" width="100" />
        <el-table-column prop="resolved" label="已解决" width="100" />
        <el-table-column prop="overdue" label="逾期" width="100" />
        <el-table-column prop="avgTime" label="平均处理时间(h)" width="150" />
        <el-table-column prop="satisfaction" label="满意度" width="100" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  TrendCharts, 
  Refresh, 
  Download, 
  FullScreen, 
  Loading, 
  DataLine 
} from '@element-plus/icons-vue'
import chartService, { chartColors } from '../services/chartService'
import dashboardApiService from '../services/dashboardApi'

export default {
  name: 'EnhancedTrendAnalysis',
  components: {
    TrendCharts,
    Refresh,
    Download,
    FullScreen,
    Loading,
    DataLine
  },
  setup() {
    const loading = ref(false)
    const timeRange = ref('week')
    const customDateRange = ref([])
    const selectedDimension = ref('status')
    const chartType = ref('line')
    
    const mainChartRef = ref(null)
    const mainChartContainerRef = ref(null)
    const statusChartRef = ref(null)
    const statusChartContainerRef = ref(null)
    const assigneeChartRef = ref(null)
    const assigneeChartContainerRef = ref(null)
    
    let mainChart = null
    let statusChart = null
    let assigneeChart = null
    
    const chartData = ref([])
    const tableData = ref([])
    
    // 加载图表数据
    const loadChartData = async () => {
      loading.value = true
      try {
        // 构建查询参数
        const params = {
          timeRange: timeRange.value,
          dimension: selectedDimension.value
        }
        
        if (timeRange.value === 'custom' && customDateRange.value && customDateRange.value.length === 2) {
          params.startDate = customDateRange.value[0]
          params.endDate = customDateRange.value[1]
        }
        
        // 调用后端API
        const data = await dashboardApiService.getTrendCharts(params)
        chartData.value = data[`${selectedDimension.value}Trend`] || []
        
        // 生成表格数据
        generateTableData()
        
        // 渲染图表
        await nextTick()
        renderCharts()
      } catch (error) {
        ElMessage.error('加载数据失败')
        console.error('加载图表数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 生成表格数据
    const generateTableData = () => {
      tableData.value = chartData.value.map(item => {
        const values = Object.values(item).filter(v => typeof v === 'number')
        const total = values.reduce((sum, val) => sum + val, 0)
        
        return {
          date: item.date || '',
          total: total,
          pending: item.pending || item.openTickets || 0,
          inProgress: item.inProgress || item.inProgressTickets || 0,
          resolved: item.resolved || item.resolvedTickets || 0,
          overdue: item.overdue || item.overdueTickets || 0,
          avgTime: (Math.random() * 10 + 5).toFixed(1),
          satisfaction: (Math.random() * 2 + 3).toFixed(1)
        }
      })
    }
    
    // 渲染所有图表
    const renderCharts = () => {
      renderMainChart()
      renderStatusChart()
      renderAssigneeChart()
    }
    
    // 渲染主图表
    const renderMainChart = () => {
      if (!mainChartRef.value || !chartData.value.length) return
      
      const labels = chartData.value.map(item => item.date || '')
      const datasets = prepareDatasets()
      
      const data = chartService.prepareChartData(labels, datasets)
      const options = getChartOptions()
      
      // 根据图表类型创建或更新图表
      if (mainChart) {
        chartService.destroyChart(mainChart)
      }
      
      if (chartType.value === 'line') {
        mainChart = chartService.createLineChart(mainChartRef.value, data, options)
      } else if (chartType.value === 'bar') {
        mainChart = chartService.createBarChart(mainChartRef.value, data, options)
      } else if (chartType.value === 'pie') {
        mainChart = chartService.createPieChart(mainChartRef.value, data, options)
      }
    }
    
    // 准备数据集
    const prepareDatasets = () => {
      if (!chartData.value.length) return []
      
      const keys = Object.keys(chartData.value[0]).filter(key => key !== 'date')
      
      return keys.map((key, index) => ({
        label: translateKey(key),
        data: chartData.value.map(item => item[key] || 0),
        backgroundColor: chartColors.gradients[index % chartColors.gradients.length],
        borderColor: chartColors.gradients[index % chartColors.gradients.length].replace('0.8', '1'),
        borderWidth: 2,
        tension: 0.4,
        fill: chartType.value === 'line' ? false : true
      }))
    }
    
    // 获取图表配置
    const getChartOptions = () => {
      const baseOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: chartType.value !== 'pie',
            position: 'top'
          },
          tooltip: {
            enabled: true,
            mode: 'index',
            intersect: false
          }
        }
      }
      
      if (chartType.value === 'pie') {
        return baseOptions
      }
      
      return {
        ...baseOptions,
        scales: {
          x: {
            grid: {
              display: false
            },
            ticks: {
              color: '#909399'
            }
          },
          y: {
            beginAtZero: true,
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            ticks: {
              color: '#909399'
            }
          }
        }
      }
    }
    
    // 渲染状态分布图表
    const renderStatusChart = () => {
      if (!statusChartRef.value || !chartData.value.length) return
      
      // 计算状态总计
      const statusTotals = {}
      chartData.value.forEach(item => {
        Object.keys(item).forEach(key => {
          if (key !== 'date') {
            statusTotals[key] = (statusTotals[key] || 0) + (item[key] || 0)
          }
        })
      })
      
      const labels = Object.keys(statusTotals).map(key => translateKey(key))
      const dataValues = Object.values(statusTotals)
      
      const data = {
        labels,
        datasets: [{
          data: dataValues,
          backgroundColor: chartColors.gradients,
          borderWidth: 0
        }]
      }
      
      const options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: true,
            position: 'right'
          }
        }
      }
      
      if (statusChart) {
        chartService.destroyChart(statusChart)
      }
      
      statusChart = chartService.createDoughnutChart(statusChartRef.value, data, options)
    }
    
    // 渲染处理人工作量图表
    const renderAssigneeChart = () => {
      if (!assigneeChartRef.value || !chartData.value.length) return
      
      // 计算处理人总计
      const assigneeTotals = {}
      chartData.value.forEach(item => {
        Object.keys(item).forEach(key => {
          if (key !== 'date') {
            assigneeTotals[key] = (assigneeTotals[key] || 0) + (item[key] || 0)
          }
        })
      })
      
      const labels = Object.keys(assigneeTotals).map(key => translateKey(key))
      const dataValues = Object.values(assigneeTotals)
      
      const data = {
        labels,
        datasets: [{
          label: '工单数量',
          data: dataValues,
          backgroundColor: chartColors.gradients,
          borderWidth: 1
        }]
      }
      
      const options = {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        plugins: {
          legend: {
            display: false
          }
        },
        scales: {
          x: {
            beginAtZero: true
          }
        }
      }
      
      if (assigneeChart) {
        chartService.destroyChart(assigneeChart)
      }
      
      assigneeChart = chartService.createBarChart(assigneeChartRef.value, data, options)
    }
    
    // 翻译键名
    const translateKey = (key) => {
      const translations = {
        pending: '待处理',
        openTickets: '待处理',
        inProgress: '处理中',
        inProgressTickets: '处理中',
        resolved: '已解决',
        resolvedTickets: '已解决',
        overdue: '逾期',
        overdueTickets: '逾期',
        system: '系统问题',
        feature: '功能问题',
        performance: '性能问题',
        other: '其他',
        agent1: '客服A',
        agent2: '客服B',
        agent3: '客服C',
        agent4: '客服D',
        high: '高优先级',
        medium: '中优先级',
        low: '低优先级'
      }
      return translations[key] || key
    }
    
    const getChartTitle = () => {
      const dimensionMap = {
        status: '工单状态趋势',
        category: '工单分类趋势',
        assignee: '处理人工作量趋势',
        priority: '工单优先级趋势'
      }
      return dimensionMap[selectedDimension.value] || '趋势分析'
    }
    
    const handleTimeRangeChange = () => {
      loadChartData()
    }
    
    const handleCustomDateChange = () => {
      if (customDateRange.value && customDateRange.value.length === 2) {
        loadChartData()
      }
    }
    
    const refreshData = () => {
      loadChartData()
    }
    
    const exportChart = () => {
      if (mainChart) {
        chartService.exportChartAsImage(mainChart, `${getChartTitle()}.png`)
      } else {
        ElMessage.info('暂无图表可导出')
      }
    }
    
    const fullscreenChart = () => {
      ElMessage.info('全屏功能开发中...')
    }
    
    const exportData = () => {
      ElMessage.info('数据导出功能开发中...')
    }
    
    // 监听维度变化
    watch(selectedDimension, () => {
      loadChartData()
    })
    
    // 监听图表类型变化
    watch(chartType, () => {
      renderMainChart()
    })
    
    // 生命周期
    onMounted(() => {
      loadChartData()
    })
    
    onUnmounted(() => {
      // 销毁所有图表实例
      if (mainChart) chartService.destroyChart(mainChart)
      if (statusChart) chartService.destroyChart(statusChart)
      if (assigneeChart) chartService.destroyChart(assigneeChart)
    })
    
    return {
      loading,
      timeRange,
      customDateRange,
      selectedDimension,
      chartType,
      mainChartRef,
      mainChartContainerRef,
      statusChartRef,
      statusChartContainerRef,
      assigneeChartRef,
      assigneeChartContainerRef,
      chartData,
      tableData,
      getChartTitle,
      handleTimeRangeChange,
      handleCustomDateChange,
      refreshData,
      exportChart,
      fullscreenChart,
      exportData
    }
  }
}
</script>

<style scoped>
.enhanced-trend-analysis {
  padding: 20px;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.filter-controls {
  display: flex;
  align-items: center;
}

.dimension-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.charts-section {
  margin-bottom: 24px;
}

.main-chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.chart-actions {
  display: flex;
  gap: 8px;
}

.chart-container {
  height: 400px;
  position: relative;
}

.chart-container canvas {
  max-height: 100%;
}

.chart-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-secondary);
}

.loading-icon {
  font-size: 24px;
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.chart-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-tertiary);
}

.chart-empty .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.secondary-charts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.secondary-chart-card .chart-container {
  height: 250px;
}

.data-table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.table-actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .enhanced-trend-analysis {
    padding: 16px;
  }
  
  .filter-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .filter-controls {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .dimension-controls {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .secondary-charts {
    grid-template-columns: 1fr;
  }
  
  .secondary-chart-card .chart-container {
    height: 200px;
  }
}

/* 暗色主题适配 */
.dark .chart-loading,
.dark .chart-empty {
  color: var(--text-secondary);
}
</style>
